package com.wisnews.controller.sec;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wisnews.pojo.Result;
import com.wisnews.pojo.sec.entity.RolePermission;
import com.wisnews.service.sec.Impl.RolePermissionServiceImpl;
import com.wisnews.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 角色对应的权限编码 前端控制器
 * </p>
 *
 * @author yuyd
 * @since 2020-12-05
 */
@RestController
@RequestMapping("/role-permission")
public class RolePermissionController {

    @Autowired
    private RolePermissionServiceImpl rolePermissionService;

    /**
     * @description: 获取所有角色-菜单
     * @param:
     * @return:
     * @author yuyd
     * @date: 2021/5/2 22:08
     */
    @RequestMapping("getAllRolePermission")
    public Result getAllRequest(){
        List<RolePermission> list = rolePermissionService.list();
        return new Result(Constants.SYS_CODE.SUCCESS,Constants.SYS_CODE.SUCCESS_MESSAGE,list);
    }


    @RequestMapping(value = "/addRolePermission/{role}",method = RequestMethod.POST)
    public Result addRolePermission(@PathVariable("role") String role,@RequestBody List<String> permissions){

        if (StringUtils.isBlank(role)) {
            return new Result(Constants.SYS_CODE.FAIL,"新增失败，参数有误！");
        }

        permissions.forEach(permission ->{
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(role);
            rolePermission.setPermissionId(permission);
            rolePermissionService.save(rolePermission);
        });

        return new Result(Constants.SYS_CODE.SUCCESS,Constants.SYS_CODE.SUCCESS_MESSAGE);
    }


    @RequestMapping(value = "/removeRolePermission/{role}",method = RequestMethod.POST)
    public Result removeRolePermission(@PathVariable("role") String role,@RequestBody List<String> permissions){

        if (StringUtils.isBlank(role)){
            return new Result(Constants.SYS_CODE.FAIL,"移除失败，参数有误！");
        }
        //移除操作
        LambdaQueryWrapper<RolePermission> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.clear();
            rolePermissionService.remove(queryWrapper.eq(RolePermission::getRoleId,role)
                    .in(RolePermission::getPermissionId,permissions));
        return new Result(Constants.SYS_CODE.SUCCESS,Constants.SYS_CODE.SUCCESS_MESSAGE);
    }
}
